<template>
  <a-modal
    :title="title"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel">
    
    <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <!-- 库存信息展示 -->
      <a-form-item label="订单号">
        <span>{{ inventoryInfo.orderNo }}</span>
      </a-form-item>
      
      <a-form-item label="门窗信息">
        <span>{{ inventoryInfo.windowSeries }} - {{ inventoryInfo.windowType }}</span>
      </a-form-item>
      
      <a-form-item label="仓库库位">
        <span>{{ inventoryInfo.warehouseName }} - {{ inventoryInfo.locationName }}</span>
      </a-form-item>
      
      <a-form-item label="当前库存">
        <div>
          <span>总数量: <strong>{{ inventoryInfo.totalQuantity }}</strong></span>
          <br/>
          <span>可用数量: <strong style="color: #52c41a;">{{ inventoryInfo.availableQuantity }}</strong></span>
          <br/>
          <span>已预留数量: <strong style="color: #faad14;">{{ inventoryInfo.reservedQuantity }}</strong></span>
        </div>
      </a-form-item>
      
      <a-divider />
      
      <!-- 释放信息输入 -->
      <a-form-item label="释放数量" :required="true">
        <a-input-number
          v-decorator="['releaseQuantity', {
            rules: [
              { required: true, message: '请输入释放数量' },
              { validator: validateReleaseQuantity }
            ]
          }]"
          :min="1"
          :max="inventoryInfo.reservedQuantity"
          :precision="0"
          style="width: 100%"
          placeholder="请输入释放数量"
        />
        <div style="color: #999; font-size: 12px; margin-top: 4px;">
          最大可释放数量: {{ inventoryInfo.reservedQuantity }}
        </div>
      </a-form-item>
      
      <a-form-item label="释放原因" :required="true">
        <a-textarea
          v-decorator="['releaseReason', {
            rules: [{ required: true, message: '请输入释放原因' }]
          }]"
          :rows="3"
          placeholder="请输入释放原因，如：订单取消、预留过期等"
        />
      </a-form-item>
      
      <a-form-item label="关联单据">
        <a-input
          v-decorator="['relatedDocNo']"
          placeholder="请输入关联单据号（可选）"
        />
      </a-form-item>
      
      <!-- 释放后预览 -->
      <a-form-item label="释放后状态">
        <div style="background: #f5f5f5; padding: 12px; border-radius: 4px;">
          <div>可用数量: {{ getAvailableAfterRelease() }}</div>
          <div>预留数量: {{ getReservedAfterRelease() }}</div>
          <div>总数量: {{ inventoryInfo.totalQuantity }}</div>
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { postAction } from '@/api/manage'

export default {
  name: 'InventoryReleaseModal',
  data() {
    return {
      title: "库存释放",
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      inventoryInfo: {}
    }
  },
  methods: {
    show(record) {
      this.visible = true;
      this.inventoryInfo = { ...record };
      this.$nextTick(() => {
        this.form.resetFields();
      });
    },
    validateReleaseQuantity(rule, value, callback) {
      if (!value) {
        callback();
        return;
      }
      
      if (value <= 0) {
        callback(new Error('释放数量必须大于0'));
        return;
      }
      
      if (value > this.inventoryInfo.reservedQuantity) {
        callback(new Error(`释放数量不能超过预留数量${this.inventoryInfo.reservedQuantity}`));
        return;
      }
      
      callback();
    },
    getAvailableAfterRelease() {
      const releaseQuantity = this.form.getFieldValue('releaseQuantity') || 0;
      return this.inventoryInfo.availableQuantity + releaseQuantity;
    },
    getReservedAfterRelease() {
      const releaseQuantity = this.form.getFieldValue('releaseQuantity') || 0;
      return Math.max(0, this.inventoryInfo.reservedQuantity - releaseQuantity);
    },
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmRelease(values);
        }
      });
    },
    async confirmRelease(values) {
      this.confirmLoading = true;
      try {
        const params = {
          inventoryId: this.inventoryInfo.id,
          releaseQuantity: values.releaseQuantity,
          releaseReason: values.releaseReason,
          relatedDocNo: values.relatedDocNo
        };

        const res = await postAction('/wms/finished-goods/inventory/release', params);
        if (res.success) {
          this.$message.success('库存释放成功');
          this.$emit('ok');
          this.close();
        } else {
          this.$message.error(res.message || '库存释放失败');
        }
      } catch (error) {
        this.$message.error('库存释放失败');
        console.error('库存释放失败', error);
      } finally {
        this.confirmLoading = false;
      }
    },
    handleCancel() {
      this.close();
    },
    close() {
      this.visible = false;
      this.confirmLoading = false;
      this.inventoryInfo = {};
      this.form.resetFields();
    }
  }
}
</script>
